package models

import (
	"github.com/jinzhu/gorm"
	"kop/libs/database"
	"kop/modules/role/configuration/level"
	"kop/modules/role/entity"
	"kop/pb"
)

func AutoMigrate() {

	database.DB.AutoMigrate(new(entity.Role))
	database.DB.AutoMigrate(new(entity.RoleDeclaration))
	database.DB.AutoMigrate(new(entity.RoleEvent))
	database.DB.AutoMigrate(new(entity.SignIn))
	database.DB.AutoMigrate(new(entity.MonthCard))
	database.DB.AutoMigrate(new(entity.Day7))
	database.DB.AutoMigrate(new(entity.RolePay))
	database.DB.AutoMigrate(new(entity.Progress))
	database.DB.AutoMigrate(new(entity.Online))
	database.DB.AutoMigrate(new(entity.OnlineStatistics))

	//var rows, err = dB.Model(&role).Limit(1).Rows()
	//	//defer rows.Close()
	//	//if err == nil {
	//	//	var columns, err = rows.Columns()
	//	//	if err == nil {
	//	//		var find = false
	//	//		for _, column := range columns {
	//	//			if column == "declaration" {
	//	//				find = true
	//	//			}
	//	//		}
	//	//		if !find {
	//	//			dB.Exec(`ALTER TABLE roles ADD COLUMN "declaration" character varying(500);
	//	//			COMMENT ON COLUMN roles.declaration IS '宣言';`)
	//	//		}
	//	//	}
	//	//}
}

// 创建角色
//func FirstOrCreate(dB *gorm.DB, userID, serverID int32) entity.Role {
//
//	var role = entity.Role{
//		UserID:    userID,
//		ServerID:  serverID,
//		Level:     1,
//		Power:     60,
//		Photo:     1,
//		Name:      "",
//		SignInNum: 1,
//	}
//
//	if err := dB.Where(entity.Role{UserID: userID, ServerID: serverID}).FirstOrCreate(&role).Error; err != nil {
//		panic(err)
//	}
//
//	return BuildPbRole(role)
//}

func GetRole(dB *gorm.DB, roleID int32) (*entity.Role, bool) {

	var data = entity.Role{RoleID: roleID}
	if err := dB.First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, false
		}
		panic(err)
	}
	return &data, true
}

func GetRoles(dB *gorm.DB, roleIDs []int32) []*pb.Role {

	var data = make([]entity.Role, 0)
	if err := dB.Find(&data, roleIDs).Error; err != nil {
		panic(err)
	}

	var res = make([]*pb.Role, 0, len(data))

	for _, v := range data {
		res = append(res, BuildPbRole(&v))
	}

	return res
}

func Save(dB *gorm.DB, role *entity.Role) {
	if err := dB.Save(&role).Error; err != nil {
		panic(err)
	}
}

func BuildPbRole(role *entity.Role) *pb.Role {

	var conf, err = level.GetByRoleLevel(role.Level)
	if err != nil {
		panic(err)
	}

	return &pb.Role{
		RoleID:   role.RoleID,
		UserID:   role.UserID,
		ServerID: role.ServerID,
		Sex:      role.Sex,
		Photo:    role.Photo,
		Level:    role.Level,
		VIP:      role.VIP,
		Name:     role.Name,
		Power:    role.Power,
		Clothing: role.Clothing,
		Position: conf.PositionCount,
	}
}
